<template>
  <div class="app-container">
    <el-form :model="productDetail" :rules="rules" label-width="100px" size="small" ref="ruleForm">
      <el-form-item label="套餐分类" prop="brandCategoryId">
        <el-select v-model="productDetail.brandCategoryId" placeholder="请选择">
          <el-option
            v-for="item,index in category"
            :key="index"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-button @click="dialogFormVisible = true">添加分类</el-button>
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input class="input-w" placeholder="请输入商品名称" v-model="productDetail.name"></el-input>
      </el-form-item>
      <el-form-item label="排序号" prop="sortNum">
        <el-input-number v-model="productDetail.sortNum" controls-position="right" :min="1" class="input-w"></el-input-number>
      </el-form-item>
      <el-form-item label="商品图片" required style="margin-bottom: 5px;">
        <el-upload
          accept="image/*"
          :action="uploadUrl"
          :headers="myHeaders"
          class="avatar-uploader"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="mainImg" :src="IMGURL + mainImg" class="avatar">
          <i class="el-icon-plus avatar-uploader-icon" v-else></i>
        </el-upload>
        <el-upload
          accept="image/*"
          :action="uploadUrl"
          :headers="myHeaders"
          class="avatar-uploader"
          :show-file-list="false"
          :on-success="handleAvatarSuccess2"
          :before-upload="beforeAvatarUpload">
          <img v-if="packageImg" :src="IMGURL + packageImg" class="avatar">
          <i class="el-icon-plus avatar-uploader-icon" v-else></i>
        </el-upload>
        <el-upload
          accept="image/*"
          :action="uploadUrl"
          :headers="myHeaders"
          class="avatar-uploader"
          :show-file-list="false"
          :on-success="handleAvatarSuccess3"
          :before-upload="beforeAvatarUpload">
          <img v-if="featureImg" :src="IMGURL + featureImg" class="avatar">
          <i class="el-icon-plus avatar-uploader-icon" v-else></i>
        </el-upload>
        <el-upload
          accept="image/*"
          :action="uploadUrl"
          :headers="myHeaders"
          class="avatar-uploader"
          :show-file-list="false"
          :on-success="handleAvatarSuccess4"
          :before-upload="beforeAvatarUpload">
          <img v-if="pointImg" :src="IMGURL + pointImg" class="avatar">
          <i class="el-icon-plus avatar-uploader-icon" v-else></i>
        </el-upload>
        <el-upload
          accept="image/*"
          :action="uploadUrl"
          :headers="myHeaders"
          class="avatar-uploader"
          :show-file-list="false"
          :on-success="handleAvatarSuccess5"
          :before-upload="beforeAvatarUpload">
          <img v-if="materialImg" :src="IMGURL + materialImg"  class="avatar">
          <i class="el-icon-plus avatar-uploader-icon" v-else></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <div>图片的顺序为：主图、包装图、特写图、卖点图、材料图</div>
      </el-form-item>
      <el-form-item label="商品描述" prop="remark">
        <el-input class="input-w" placeholder="请输入商品描述" v-model="productDetail.remark" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="商品标签" prop="categoryID">
        <el-cascader
          expand-trigger="hover"
          :options="categoryOptions"
          v-model="productDetail.categoryID"
          @change="handleChange">
        </el-cascader>
      </el-form-item>
      <el-form-item :label="item.attributeName" v-for="item,index in tagOptions" :key="index" label-width="120px">
        <el-select placeholder="请选择" v-model="item.valueId" v-if="item.type === '1'">
          <el-option
            v-for="item1,index1 in item.attributeValues"
            :key="index1"
            :label="item1.attrivuteValue"
            :value="item1.id">
          </el-option>
        </el-select>
        <el-select v-model="item.valueId" multiple placeholder="请选择" v-else-if="item.type === '2'">
          <el-option
            v-for="(item2,index2) in item.attributeValues"
            :key="index2"
            :label="item2.attrivuteValue"
            :value="item2.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品类型" prop="title" class="form-item">
        <el-row :gutter="20" class="goods-add-type" v-for="(item4,index4) in goodsType" :key="index4">
          <el-col :span="4" v-if="goodsType.length > 1">
            <h1>规格</h1>
            <el-popover
              placement="top-start"
              width="200"
              trigger="click">
              <el-button v-for="(item3,index3) in specificationsList" :key="index3" class="goods-tag" @click="saveTag(item3, item4)">{{item3.attrivuteValue}}</el-button>
              <el-button slot="reference" @click="specifications"><el-input readonly v-model="item4.name"></el-input></el-button>
            </el-popover>
          </el-col>
          <el-col :span="4">
            <h1>价格</h1>
            <el-input-number v-model="item4.price" controls-position="right" :min="1"></el-input-number>
          </el-col>
          <el-col :span="4">
            <h1>库存</h1>
            <el-input-number v-model="item4.stock" controls-position="right" :min="1"></el-input-number>
            <!--<el-input style="width: 50%;" placeholder="每日" v-model="item4.day"></el-input>-->
          </el-col>
          <el-col :span="4">
            <h1>排序号</h1>
            <el-input-number v-model="item4.sortNum" controls-position="right" :min="1" style="width: 80%;"></el-input-number>
            <!--<el-input v-model="item4.sortNum"></el-input>-->
            <i class="el-icon-error" style="cursor: pointer;margin-left: 10px" @click="colseGoodsType(index4)" v-if="goodsType.length > 1"></i>
          </el-col>
          <!--<el-col :span="4">-->
            <!--<h1> </h1>-->
            <!---->
          <!--</el-col>-->
        </el-row>
        <el-button @click="addGoodsType">添加规格</el-button>
      </el-form-item>
      <el-form-item label="是否特色" prop="characteristic">
        <el-radio-group v-model="productDetail.characteristic">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="包装费" prop="packagePrice">
        <el-input-number v-model="productDetail.packagePrice" controls-position="right" :min="0" class="input-w"></el-input-number>
      </el-form-item>
      <el-form-item class="dialog-footer">
        <!--<div slot="footer">-->
        <el-button @click="handleBack">返 回</el-button>
        <el-button type="primary"  @click="submitForm('ruleForm')">确 定</el-button>
        <!--</div>-->
      </el-form-item>
    </el-form>

    <el-dialog title="添加分类" :visible.sync="dialogFormVisible">
      <el-form :model="categoryAdd" size="small">
        <el-form-item label="分类名称" label-width="100px">
          <el-input v-model="categoryAdd.name" auto-complete="off" class="input-w"></el-input>
        </el-form-item>
        <el-form-item label="分类描述" label-width="100px">
          <el-input v-model="categoryAdd.description" auto-complete="off" class="input-w"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import ElsUpload from '../../../components/element-r/upload/index'
  import { goods_category_list, goods_categpry_add, goods_categpry_tag, goods_categpry_all, goods_specifications, goods_add, goods_detail, goods_change } from '../../../api/index'
  import { IMGURL } from '@/utils/imgurl'
  import { UPLOADURL } from '@/utils/uploadurl'

  export default {
    components: {
      ElsUpload
    },
    data() {
      return {
        IMGURL: IMGURL,
        formFlag: false,
        goodsType: [
          { name: '', price: 0, stock: 0, sortNum: 0, attributeNameId: 0, attributeValueId: 0, id: '' }
        ],
        productDetail: {
          characteristic: 2
        }, // 商品详情
        productImg: {}, // 商品图片
        attributeRelatesList: [], // 产品标签
        myHeaders: { Authorization: getToken() },
        uploadUrl: UPLOADURL,
        thumbs: [],
        tagOptions: [],
        types: [{}, {}, {}],
        categoryOptions: [],
        categoryAdd: {},
        category: [],
        dialogFormVisible: false,
        rules: {
          packagePrice: [
            { required: true, message: '请输入包装盒价格', trigger: 'blur' }
          ],
          remark: [
            { required: true, message: '请输入商品描述', trigger: 'blur' }
          ],
          sortNum: [
            { required: true, message: '请输入排序号', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          categoryID: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          brandCategoryId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          characteristic: [
            { required: true, message: '请选择', trigger: 'change' }
          ]
        },
        //
        specificationsList: [],
        projectId: 0,
        mainImg: '', // 主图
        packageImg: '', // 包装图
        featureImg: '', // 特写图
        pointImg: '', // 卖点图
        materialImg: '', // 材料图
        testList: []
      }
    },
    methods: {
      handleAvatarSuccess(res, file) {
        console.log('--------------')
        console.log(res)
        this.mainImg = res.data
      },
      handleAvatarSuccess2(res, file) {
        console.log('--------------')
        console.log(res)
        this.packageImg = res.data
      },
      handleAvatarSuccess3(res, file) {
        console.log('--------------')
        console.log(res)
        this.featureImg = res.data
      },
      handleAvatarSuccess4(res, file) {
        console.log('--------------')
        console.log(res)
        this.pointImg = res.data
      },
      handleAvatarSuccess5(res, file) {
        console.log('--------------')
        console.log(res)
        this.materialImg = res.data
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isLt2M
      }, //
      handleChange(value) {
        console.log(value)
        this.getTag(value[0])
      },
      submitForm(formName) {
        this.attributeRelatesList = []
        this.tagOptions.forEach(item => {
          if (item.valueId !== '') {
            this.attributeRelatesList.push({ attributeNameId: item.attributeNameId, attributeValueId: item.valueId, asSku: 2 })
          }
        })
        this.productImg = {
          mainImg: this.mainImg,
          packageImg: this.packageImg,
          featureImg: this.featureImg,
          pointImg: this.pointImg,
          materialImg: this.materialImg
        }
        this.productDetail.mainImgKey = this.mainImg
        if (!this.productDetail.mainImgKey) {
          this.$message({ type: 'warning', message: '请上传商品主图' })
          return
        }
        if (this.goodsType.length === 0) {
          this.$message({ type: 'warning', message: '请填写规格' })
          return
        }
        if (this.goodsType.length === 1) {
          this.goodsType[0].name = ''
          this.goodsType[0].sizeName = ''
          this.goodsType[0].sizeValue = ''
          this.goodsType[0].attributeValueId = ''
          this.goodsType[0].attributeNameId = ''
        }
        if (this.goodsType.length > 1) {
          this.goodsType.forEach(item => {
            if (!item.name) {
              this.$message({ type: 'warning', message: '请选择规格' })
              this.formFlag = true
            } else {
              this.formFlag = false
            }
          })
        }
        if (this.formFlag) {
          return
        }
        console.log(111111111)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.productDetail.categoryId = this.productDetail.categoryID[0]
            const params = {
              id: this.projectId,
              productDetail: this.productDetail,
              productImg: this.productImg,
              attributeRelatesList: this.attributeRelatesList,
              skuList: this.goodsType
            }
            console.log(params, 88888888888888888888888)
            if (this.projectId) {
              goods_change(params).then(res => {
                console.log(res)
                this.$message({ type: 'success', message: '修改成功' })
                this.$router.go(-1)
              })
            } else {
              goods_add(params).then(res => {
                console.log(res)
                this.$message({ type: 'success', message: '添加成功' })
                this.$router.go(-1)
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      getInfo(id) {
        const params = {
          id: id
        }
        goods_detail(params).then(res => {
          console.log(res, 8888)
          this.productDetail = res.productDetail
          this.productDetail.categoryID = []
          this.productDetail.categoryID[0] = res.productDetail.categoryId
          this.mainImg = res.productImg.mainImg
          this.packageImg = res.productImg.packageImg
          this.featureImg = res.productImg.featureImg
          this.pointImg = res.productImg.pointImg
          this.materialImg = res.productImg.materialImg
          var name = []
          res.productSkuList.forEach(item => {
            res.attributeRelatesList.forEach(item1 => {
              // if (item.id === item1.skuId) {
              //   name.push({ id: item.id, nameId: item1.attributeNameId, valueId: item1.attributeValueId })
              // }
              name.push({ id: item.id, nameId: item1.attributeNameId, valueId: item1.attributeValueId })
            })
          })
          res.attributeDtoList.forEach(item => {
            name.forEach(item1 => {
              if (item.attributeNameId === item1.nameId) {
                item1.name = item.attributeName
                item1.type = item.type
              }
            })
          })
          res.attributeDtoList.forEach(item => {
            item.attributeValues.forEach(item1 => {
              name.forEach(item2 => {
                if (item1.id === item2.valueId) {
                  item2.value = item1.attrivuteValue
                }
              })
            })
          })
          var size = []
          res.productSkuList.forEach(item => {
            res.skuAttributeList.forEach(item1 => {
              if (item.id === item1.skuId) {
                size.push({ id: item.id, attributeNameId: item1.attributeNameId, attributeValueId: item1.attributeValueId, price: item.price, sortNum: item.sortNum, stock: item.stock })
              }
            })
          })
          res.attributeDtoList.forEach(item => {
            size.forEach(item1 => {
              if (item.attributeNameId === item1.attributeNameId) {
                item1.sizeName = item.attributeName
              }
            })
          })
          res.attributeDtoList.forEach(item => {
            item.attributeValues.forEach(item1 => {
              size.forEach(item2 => {
                if (item1.id === item2.attributeValueId) {
                  item2.sizeValue = item1.attrivuteValue
                }
              })
            })
          })
          console.log(name, 1)
          console.log(size, 2)
          this.goodsType = size
          for (let i = 0; i < size.length; i++) {
            this.goodsType[i].name = size[i].sizeValue
          }
          for (let i = 0; i < res.productSkuList.length; i++) {
            this.goodsType[i]
          }
          console.log(this.goodsType, 5586)
          this.testList = []
          this.testList = name
          // for (let i = 0; i < name.length / 2; i++) {
          //   this.testList.push(name[i])
          // }
          console.log(res.productDetail.categoryId)
          console.log('=====================================')
          this.getTag(res.productDetail.categoryId)
        })
      },
      handleBack() {
        this.$router.go(-1)
      },
      getCategoryList() {
        goods_category_list().then(res => {
          console.log(res, 88)
          this.category = res.brandProductCategoryList
        })
      },
      addCategory() {
        this.dialogFormVisible = false
        goods_categpry_add(this.categoryAdd).then(res => {
          console.log(res)
          this.$message({ type: 'success', message: '添加成功' })
          this.getCategoryList()
        })
      },
      getCategory() { // 标签分类
        goods_categpry_all().then(res => {
          // console.log(res, 1)
          var list = []
          res.productCategoryList.forEach(item => {
            list.push({ value: item.id, label: item.name })
          })
          this.categoryOptions = list
        })
      },
      getTag(id) { // 主料辅料...
        const params = {
          id: id
        }
        goods_categpry_tag(params).then(res => {
          console.log(res, 96)
          res.forEach(item => {
            item.valueId = ''
          })
          console.log(this.testList, 1)
          if (this.testList.length > 0) {
            this.testList.forEach(item => {
              res.forEach(item1 => {
                if (item.nameId === item1.attributeNameId) {
                  item1.valueId = item.valueId
                }
              })
            })
          }
          this.tagOptions = res
          console.log(this.tagOptions, 8)
        })
      },
      specifications() { // 商品规格
        const params = {
          id: 1
        }
        goods_specifications(params).then(res => {
          console.log(res, 23)
          this.specificationsList = res
        })
      },
      addGoodsType() {
        this.goodsType.push({ name: '', price: 0, stock: 0, sortNum: 0, attributeNameId: 0, attributeValueId: 0 })
      },
      colseGoodsType(index) {
        console.log(index)
        this.goodsType.splice(index, 1)
      },
      saveTag(item3, item4) {
        item4.name = item3.attrivuteValue
        item4.attributeNameId = item3.attributeNameId
        item4.attributeValueId = item3.id
        console.log(item4, 416565465)
      }
    },
    mounted() {
      this.getCategory()
      this.getCategoryList()
      this.$route.params.id = parseInt(this.$route.params.id)
      if (this.$route.params.id !== 0) {
        console.log(123)
        this.projectId = this.$route.params.id
        this.getInfo(this.$route.params.id)
      }
    }
  }
</script>

<style src="./detail.scss" lang="scss" scoped></style>
